package com.example.demo.config;

import com.example.demo.vo.RespInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常配置类
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionConfig {

    /**
     * 所有异常报错后会走这个方法，处理之后响应信息
     *
     * @param req 参数
     * @param e   异常
     * @return 返回
     * @throws Exception 异常
     */
    @ExceptionHandler(value = Exception.class)
    public RespInfo allExceptionHandler(HttpServletRequest req, Exception e) throws Exception {
        RespInfo respInfo = new RespInfo();
        if (e instanceof ApiException) {
            ApiException tmp = (ApiException) e;
            respInfo.setRet(tmp.getRet(), tmp.getMessage());
        } else {
            log.info("打印报错日志", e);
            respInfo.setRet(RetEnum.Failed);
        }
        return respInfo;
    }


}
